<template>
  <div>
    <van-form @submit="userLogin">
      <van-cell-group inset>
        <van-field v-model="user.username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[
            { required: true, message: '请填写用户名' },
            {
              pattern: /^[a-z]\w{3,7}$/,
              message: '4到8位英文数字字母_组成,必须小写字母开头'
            }
          ]" />
        <van-field v-model="user.pwd" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <van-button @click="router.push('/reg')">去注册</van-button>
  </div>
</template>

<script setup lang="ts" name="Login">
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import { doLogin } from '@a/index'
import { showToast } from 'vant';
import useUserStore from '@s/user'

const router = useRouter();
// piania user仓库
const userStore = useUserStore();

const user: { username: string, pwd: string } = reactive({
  username: '',
  pwd: ''
})
// 用户登录
const userLogin = () => {
  doLogin({
    ...user,
    deviceId: 'qwer',
    deviceName: 'dwferg4'
  }).then(res => {
    if(res.data.code === 0) {
      // 将用户个人信息缓存 最好存储到piania
      localStorage.setItem('uid', res.data.data.uid)
      localStorage.setItem('token', res.data.data.token)
      userStore.$patch({
        uid: res.data.data.uid,
        token: res.data.data.token
      })
      showToast({
        type: 'success',
        message: '用户登录成功',
        duration: 1500,
        onClose: () => {
          router.replace('/')
        }
      })
    }
    if (res.data.code === 500) {
      showToast({
        type: 'fail',
        message: res.data.msg,
        duration: 1500
        
      })
    }
    
  })
}
</script>

<style scoped>

</style>